<template>
  <div class="m-4 mr-0 mt-0 overflow-hidden bg-white">
    <BasicTree
      defaultExpandAll
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      :clickRowToExpand="false"
      :treeData="treeData"
      :fieldNames="{ key: 'id', title: 'name' }"
      @select="handleSelect"
      ref="asyncExpandTreeRef"
    />
  </div>
</template>
<script lang="ts" setup>
  import { ref, unref, nextTick } from 'vue';

  import { BasicTree, TreeActionType, TreeItem } from '/@/components/Tree';
  import { getDeptTreeByPage } from '/@/api/admin/dept';

  const emit = defineEmits(['select']);
  const treeData = ref<TreeItem[]>([]);
  const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);

  async function fetch() {
    const children = (await getDeptTreeByPage()) as unknown as TreeItem[];
    // treeData.value = [
    //   {
    //     id: '',
    //     key: '-1',
    //     name: '所有部门',
    //     children,
    //   },
    // ];
    treeData.value = children;
    nextTick(() => {
      unref(asyncExpandTreeRef)?.expandAll(true);
    });
  }
  fetch();

  function getTree() {
    const tree = unref(asyncExpandTreeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }

  async function handleSetSelectData(key) {
    getTree().setSelectedKeys([key]);
    await fetch();
    emit('select', key, treeData.value);
  }

  function handleSelect(keys) {
    emit('select', keys[0], treeData.value);
  }

  defineExpose({
    handleSetSelectData,
  });
</script>
